package com.yikaiye.android.yikaiye.ui.activity.order;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.yikaiye.android.yikaiye.R;
import com.yikaiye.android.yikaiye.application.MyApplication;
import com.yikaiye.android.yikaiye.base.BaseActivity;
import com.yikaiye.android.yikaiye.config.Constant;
import com.yikaiye.android.yikaiye.databinding.ActivityOrderDetailsBinding;
import com.yikaiye.android.yikaiye.dialog.MyDialog;
import com.yikaiye.android.yikaiye.dialog.VerifiedDialog;
import com.yikaiye.android.yikaiye.http.ApiFactory;
import com.yikaiye.android.yikaiye.model.CheckComboResponseModel;
import com.yikaiye.android.yikaiye.model.CheckModel;
import com.yikaiye.android.yikaiye.model.ChooseServiceModel;
import com.yikaiye.android.yikaiye.model.CommitOrderModel;
import com.yikaiye.android.yikaiye.model.EventBusModel;
import com.yikaiye.android.yikaiye.model.OrderProductModel;
import com.yikaiye.android.yikaiye.model.PayResult;
import com.yikaiye.android.yikaiye.pay.WeChatPay;
import com.yikaiye.android.yikaiye.ui.activity.home.ConfirmOrderActivity;
import com.yikaiye.android.yikaiye.ui.activity.home.ProductDetailsActivity;
import com.yikaiye.android.yikaiye.ui.activity.home.viewmodel.ConfirmOrderViewModel;
import com.yikaiye.android.yikaiye.ui.adapter.EmptyRecyclerCommonAdapter;
import com.yikaiye.android.yikaiye.ui.adapter.RecyclerViewHolder;
import com.yikaiye.android.yikaiye.utils.CommonUtil;
import com.yikaiye.android.yikaiye.utils.JumpIntent;
import com.yikaiye.android.yikaiye.utils.ToastHelper;
import com.yikaiye.android.yikaiye.utils.UMengUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单详情
 */
public class OrderDetailsActivity extends BaseActivity<ActivityOrderDetailsBinding, ConfirmOrderViewModel> {

    private static final int SDK_PAY_FLAG = 1;
    private String id;
    /**
     * 0支付宝、1微信
     */
    private int payType = 0;
    private MyDialog myDialog;

    private OrderProductModel orderProductModel;
    private String from;

    @Override
    protected ConfirmOrderViewModel bindModel() {
        return getViewModel(this, ConfirmOrderViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void initData() {
        initTitleBar(getString(R.string.order_details));
        if (null != getIntent().getExtras()) {
            id = getIntent().getExtras().getString(Constant.ID_KEY);
            from = getIntent().getExtras().getString(Constant.FROM_KEY);
            viewModel.getOrderDetails(id);
        }
        binding.tvAutoCancelOrder.setSelected(true);
        initDialog();
    }

    @Override
    protected void initClick() {
        viewModel.orderDetailsMutableLiveData.observe(this, productModel -> {
            if (productModel != null) {
                this.orderProductModel = productModel;
                if (TextUtils.isEmpty(productModel.getCompName())) {
                    binding.rlCompanyName.setVisibility(View.GONE);
                } else {
                    binding.rlCompanyName.setVisibility(View.VISIBLE);
                    binding.tvCompanyName.setText(productModel.getCompName());
                }
                binding.tvProductTitle.setText(CommonUtil.checkText(productModel.getProductName()));
                binding.tvProductPrice.setText(String.format(getString(R.string.price), productModel.getPrice()));
                binding.includeService.tvServiceTotalPrice.setText(getString(R.string.total_price, productModel.getCostPrice()));
                binding.includeService.tvServiceRealPrice.setText(CommonUtil.checkText(productModel.getEnterState() == 1 ? productModel.getPrice() : productModel.getAppPrice()));
                binding.tvTotalPrice.setText(String.format(getString(R.string.price), productModel.getPrice()));
                binding.tvOrderNo.setText(CommonUtil.checkText(productModel.getOrderNo()));
                binding.tvCreateTime.setText(CommonUtil.checkText(productModel.getCreateTime()));
                binding.tvBuyTime.setText(CommonUtil.checkText(productModel.getOrderTime()));
                binding.tvProductDes.setText(CommonUtil.checkText(productModel.getSlogan()));
                Glide.with(MyApplication.getContext()).load(ApiFactory.BASE_IMAGE_URL + productModel.getAppBanner()).placeholder(R.mipmap.default_image).error(R.mipmap.default_image).into(binding.ivProductImg);
                List<CheckComboResponseModel.ServiceAttrModel> items = productModel.getServiceInfos();
                if (null != items) {
                    initCtrl(items);
                }

                // 订单状态，0：待付款，1：已付款，2：已取消，3：已退款，4：超时
                switch (productModel.getStatus()) {
                    case 0: // 0：待支付
                        binding.tvOrderStatus.setText(context.getString(R.string.wait_payment));
                        binding.tvOrderStatus.setTextColor(ContextCompat.getColor(context, R.color.color_f93f50));
                        binding.llBottomButton.setVisibility(View.VISIBLE);
                        // source  0:线上订单，1：线下订单.待付款线下订单（非预订单）的订单，不显示“取消订单”按钮
                        binding.tvBtnStatus.setVisibility(productModel.getSource() == 0 ? View.VISIBLE : View.GONE);
                        binding.tvBtnStatus.setText(context.getString(R.string.cancel_order));
                        binding.tvProtocol.setVisibility(View.GONE);
                        binding.tvToPay.setVisibility(View.VISIBLE);
                        binding.llTotalPrice.setVisibility(View.VISIBLE);
                        binding.includePay.llPayWay.setVisibility(View.VISIBLE);
                        break;
                    case 1: // 1：已付款（contractSignStatus--> 0：未签署；1：签署处理中；2:签署成功，3:签署失败）
                        binding.tvOrderStatus.setText(context.getString(R.string.already_pay));
                        binding.tvOrderStatus.setTextColor(ContextCompat.getColor(context, R.color.black));
                        binding.llBottomButton.setVisibility(View.VISIBLE);
                        binding.tvBtnStatus.setVisibility(View.VISIBLE);
                        binding.tvBtnStatus.setText(context.getString(R.string.look_progress));
                        binding.tvToPay.setVisibility(View.GONE);
                        binding.includePay.llPayWay.setVisibility(View.GONE);
                        // showContract为1时，正常显示合同相关信息，比如签署，查看等等，反之不显示合同相关信息
                        if (productModel.getShowContract() != null && productModel.getShowContract() == 1) {
                            // 0：未签署；1：签署处理中；2:签署成功，3:签署失败
                            if (productModel.getContractSignStatusNew() != null) {
                                if (2 == productModel.getContractSignStatusNew()) {
                                    binding.tvProtocol.setVisibility(View.VISIBLE);
                                    binding.tvProtocol.setText(context.getString(R.string.look_e_agreement));
                                    binding.tvProtocol.setTextColor(ContextCompat.getColor(context, R.color.color_3b3a40));
                                    binding.tvProtocol.setBackgroundResource(R.drawable.shape_stroke_d7d7d7_4dp);
                                } else {
                                    binding.tvProtocol.setVisibility(View.VISIBLE);
                                    binding.tvProtocol.setText(context.getString(R.string.sign_agreements));
                                    binding.tvProtocol.setTextColor(ContextCompat.getColor(context, R.color.color_f93f50));
                                    binding.tvProtocol.setBackgroundResource(R.drawable.shape_stroke_f93f50_4dp);
                                }
                            } else {
                                binding.tvProtocol.setVisibility(View.GONE);
                            }
                        } else {
                            binding.tvProtocol.setVisibility(View.GONE);
                        }
                        break;
                    case 2: // 2：已取消
                        binding.tvOrderStatus.setText(context.getString(R.string.already_cancel));
                        binding.tvOrderStatus.setTextColor(ContextCompat.getColor(context, R.color.black));
                        binding.llBottomButton.setVisibility(View.VISIBLE);
                        binding.tvBtnStatus.setVisibility(View.GONE);
                        binding.tvToPay.setVisibility(View.VISIBLE);
                        binding.tvToPay.setText(getString(R.string.order_again2));
                        binding.tvProtocol.setVisibility(View.GONE);
                        binding.includePay.llPayWay.setVisibility(View.GONE);
                        break;
                    case 4: // 4：超时
                        binding.tvOrderStatus.setText(context.getString(R.string.timeout));
                        binding.tvOrderStatus.setTextColor(ContextCompat.getColor(context, R.color.color_f93f50));
                        binding.llBottomButton.setVisibility(View.GONE);
                        binding.includePay.llPayWay.setVisibility(View.GONE);
                        break;
                }
            }
        });

        viewModel.onDelayClick(binding.tvBtnStatus, o -> {
            if (binding.tvBtnStatus.getText().toString().equals(context.getString(R.string.cancel_order))) { // 取消订单
                UMengUtil.setCountEventPage(Constant.ORDER_CANCEL, getString(R.string.order_details));
                if (null != myDialog) {
                    myDialog.showDialog();
                }
            } else if (binding.tvBtnStatus.getText().toString().equals(context.getString(R.string.look_progress))) { // 查看进度
                if (from.equals(Constant.order)) {
                    EventBus.getDefault().post(new EventBusModel(Constant.finishServiceDetailsPage));
                    finish();
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString(Constant.ID_KEY, orderProductModel.getId());
                    bundle.putString(Constant.FROM_KEY, from);
                    JumpIntent.jump(this, LookOrderProgressActivity.class, bundle);
                }
            }
        });

        viewModel.onDelayClick(binding.tvProtocol, o -> {
            if (binding.tvProtocol.getText().toString().equals(context.getString(R.string.sign_e_agreement))) {
                if (orderProductModel != null) {
                    viewModel.queryVerifyResult(orderProductModel.getOrderNo(), orderProductModel.getCustomerType());
                }
            } else if (binding.tvProtocol.getText().toString().equals(context.getString(R.string.look_e_agreement))) {
                if (orderProductModel != null) {
                    viewModel.lookView(orderProductModel.getOrderNo());
                }
            }
        });

        viewModel.onDelayClick(binding.tvToPay, o -> {
            if (binding.tvToPay.getText().equals(getString(R.string.order_again2))) {
                // 再次下单逻辑： 重新下单-->检查套餐——>是：确定订单页 否：到产品详情页——>点击立即下单按钮
                showLoadingDialog();
                List<CheckComboResponseModel.ServiceAttrModel> items = orderProductModel.getServiceInfos();
                if (items != null) {
                    List<ChooseServiceModel> chooseServiceList = new ArrayList<>();
                    for (CheckComboResponseModel.ServiceAttrModel serviceModel : items) {
                        ChooseServiceModel chooseServiceModel = new ChooseServiceModel();
                        chooseServiceModel.setServiceId(serviceModel.getServiceId());
                        chooseServiceModel.setServiceName(serviceModel.getServiceName());
                        String[] s = serviceModel.getSelectInfo().split("-");
                        List<String> remarks = new ArrayList<>(Arrays.asList(s));
                        chooseServiceModel.setRemarks(remarks);

                        if (serviceModel.getBookPeriod() > 1) {
                            chooseServiceModel.setServiceAttrCycle(String.valueOf(serviceModel.getBookPeriod()));
                        }
                        chooseServiceList.add(chooseServiceModel);
                    }
                    CheckModel checkModel = new CheckModel();
                    checkModel.setProductId(orderProductModel.getProductId());
                    checkModel.setProductReqs(chooseServiceList);
                    viewModel.checkProduct(checkModel);
                }
            } else {
                UMengUtil.setCountEventId(Constant.ORDER_TO_PAY);
                Map<String, Object> map = new HashMap<>();
                map.put("enterConfirmState", 1);
                map.put("companyName", orderProductModel.getCompName());
                map.put("creditNo", orderProductModel.getCreditNo());
                if (payType == 0) {
                    viewModel.getAliPay(id, new Gson().toJson(map));
                } else {
                    if (!MyApplication.wxapi.isWXAppInstalled()) {
                        ToastHelper.show(getString(R.string.please_install_wechat));
                        return;
                    }
                    viewModel.getWeChatPay(id, new Gson().toJson(map));
                }
            }
        });
        viewModel.onDelayClick(binding.includePay.rlZhi, o -> {
            payType = 0;
            binding.includePay.ivZhiStatus.setImageResource(R.mipmap.icon_duigou_sel);
            binding.includePay.ivWeStatus.setImageResource(R.mipmap.icon_duigou_def);
        });
        viewModel.onDelayClick(binding.includePay.rlWe, o -> {
            payType = 1;
            binding.includePay.ivZhiStatus.setImageResource(R.mipmap.icon_duigou_def);
            binding.includePay.ivWeStatus.setImageResource(R.mipmap.icon_duigou_sel);
        });

        // 订单取消成功
        viewModel.orderCancelSuccessMutableLiveData.observe(this, s -> {
            viewModel.getOrderDetails(id);
            ToastHelper.show(getString(R.string.cancel_order_success));
            EventBus.getDefault().post(new EventBusModel(Constant.refresh_order));
        });

        // 订单取消失败
        viewModel.orderCancelErrorMutableLiveData.observe(this, s -> {
            ToastHelper.show(s);
            dismissLoadingDialog();
        });

        // 检查套餐存在
        viewModel.checkResponseModelMutableLiveData.observe(this, checkComboResponseModel -> {
            dismissLoadingDialog();
            if (null != checkComboResponseModel) {
                CommitOrderModel commitOrderModel = new CommitOrderModel();
                commitOrderModel.setProductId(orderProductModel.getProductId());
                commitOrderModel.setProductName(orderProductModel.getProductName());
                commitOrderModel.setPrice(checkComboResponseModel.getProductPrice());
                // android传2
                commitOrderModel.setPlatform(2);
                // 订单类型：2=预订单
                commitOrderModel.setType(2);
                commitOrderModel.setStatus(0);
                commitOrderModel.setVersion("1");
                commitOrderModel.setSource(0);

                for (CheckComboResponseModel.ServiceAttrModel serviceAttrModel : checkComboResponseModel.getProductServiceAttrLists()) {
                    CommitOrderModel.Item item = new CommitOrderModel.Item();
                    item.setServiceId(serviceAttrModel.getServiceId());
                    item.setSelectInfo(serviceAttrModel.getTerminalName());
                    item.setSelectInfoId(serviceAttrModel.getAttrListId());
                    item.setServiceName(serviceAttrModel.getServiceName());
                    item.setPrice(serviceAttrModel.getServiceAttrPrice());
                    item.setBookPeriod(serviceAttrModel.getServiceAttrCycle());
                    item.setProductAttrListId(serviceAttrModel.getId());

                    item.setServiceType(serviceAttrModel.getServiceType());
                    item.setServiceAttrCycleType(serviceAttrModel.getServiceAttrCycleType());
                    item.setTerminalName(serviceAttrModel.getTerminalName());
                    commitOrderModel.getItems().add(item);
                }
                Bundle bundle = new Bundle();
                bundle.putString(Constant.DES_KEY, orderProductModel.getSlogan());
                bundle.putString(Constant.IMG_KEY, orderProductModel.getAppBanner());
                bundle.putSerializable(Constant.MODEL_KEY, commitOrderModel);
                JumpIntent.jump(this, ConfirmOrderActivity.class, bundle);
            }
        });

        // 检查套餐不存在或报错
        viewModel.checkErrorMutableLiveData.observe(this, s -> {
            dismissLoadingDialog();
            Bundle bundle = new Bundle();
            bundle.putString(Constant.ID_KEY, orderProductModel.getProductId());
            JumpIntent.jump(this, ProductDetailsActivity.class, bundle);
        });

        // 微信支付
        viewModel.wechatPaySuccessMutableLiveData.observe(this, weChatInfoModel -> {
            dismissLoadingDialog();
            new WeChatPay().pay(context, weChatInfoModel);
            Bundle bundle = new Bundle();
            bundle.putInt(Constant.RESULT_STATUS_KEY, 1);
            JumpIntent.jump(this, OrderResultActivity.class, bundle);
        });
        viewModel.wechatPayErrorMutableLiveData.observe(this, s -> {
            dismissLoadingDialog();
            Bundle bundle = new Bundle();
            bundle.putInt(Constant.RESULT_STATUS_KEY, -1);
            JumpIntent.jump(this, OrderResultActivity.class, bundle);
        });

        // 支付宝
        viewModel.aliPaySuccessMutableLiveData.observe(this, alipayModel -> {
            dismissLoadingDialog();
            alipay(alipayModel.getBody());
        });
        viewModel.aliPayErrorMutableLiveData.observe(this, s -> {
            dismissLoadingDialog();
            Bundle bundle = new Bundle();
            bundle.putInt(Constant.RESULT_STATUS_KEY, -1);
            JumpIntent.jump(this, OrderResultActivity.class, bundle);
        });

        // 查看合同
        viewModel.lookViewFddModelMutableLiveData.observe(this, fddModel -> {
            if (fddModel != null && fddModel.getResult() != null) {
                String url = fddModel.getResult().getUrl();
                Bundle bundle = new Bundle();
                bundle.putString(Constant.URL_KEY, url);
                JumpIntent.jump(this, FaDaDaActivity.class, bundle);
                dismissLoadingDialog();
            }
        });
        viewModel.lookViewErrorMutableLiveData.observe(this, s -> dismissLoadingDialog());

        // 查询认证结果认证
        viewModel.queryResultFddModelMutableLiveData.observe(this, fddModel -> {
            if (null != fddModel) {
                // 00-处理成功；01-处理中；02-处理失败；03-未开始实名认证；04-人工审核中
                if ("00".equals(fddModel.getRespCode())) {
                    // 签署电子协议--/api/yky/app/fdd/signContract/{orderNo}/sign
                    showLoadingDialog();
                    viewModel.signContract(orderProductModel.getOrderNo(), orderProductModel.getCustomerType());
                } else if ("02".equals(fddModel.getRespCode())) {
                    // 重新认证--/api/yky/app/fdd/identityVerify/verify/reset
                    initVerifyDialog(orderProductModel.getOrderNo(), true, orderProductModel.getCustomerType());
                } else if ("04".equals(fddModel.getRespCode())) {
                    ToastHelper.show(getString(R.string.real_name_review));
                } else {
                    // 实名认证--/api/yky/app/fdd/identityVerify/verify
                    initVerifyDialog(orderProductModel.getOrderNo(), false, orderProductModel.getCustomerType());
                }
            }
            dismissLoadingDialog();
        });
        viewModel.queryResultErrorMutableLiveData.observe(this, s -> dismissLoadingDialog());

        // 签署电子协议
        viewModel.signFddModelMutableLiveData.observe(this, fddModel -> {
            if (fddModel != null && fddModel.getResult() != null) {
                String url = fddModel.getResult().getUrl();
                Bundle bundle = new Bundle();
                bundle.putString(Constant.URL_KEY, url);
                JumpIntent.jump(this, FaDaDaActivity.class, bundle);
            }
            dismissLoadingDialog();
        });
        viewModel.signErrorMutableLiveData.observe(this, s -> dismissLoadingDialog());

        // 实名认证/重新实名认证
        viewModel.verifyFddModelMutableLiveData.observe(this, fddModel -> {
            if (fddModel != null && fddModel.getResult() != null) {
                String url = fddModel.getResult().getUrl();
                Bundle bundle = new Bundle();
                bundle.putString(Constant.URL_KEY, url);
                JumpIntent.jump(this, FaDaDaActivity.class, bundle);
            }
            dismissLoadingDialog();
        });
        viewModel.verifyErrorMutableLiveData.observe(this, s -> dismissLoadingDialog());
    }

    private void initVerifyDialog(String orderNo, boolean isReset, int customerType) {
        VerifiedDialog verifiedDialog = new VerifiedDialog(this) {
            @Override
            public void verify() {
                showLoadingDialog();
                if (isReset) {
                    viewModel.resetVerify(orderNo, customerType);
                } else {
                    viewModel.realNameVerify(orderNo, customerType);
                }

                dismissDialog();
            }
        };
        verifiedDialog.showDialog();
    }

    private void initDialog() {
        myDialog = new MyDialog(this) {
            @Override
            public void leftClick() {
                dismissDialog();
            }

            @Override
            public void rightClick() {
                viewModel.cancelOrder(id);
                dismissDialog();
            }
        };
        myDialog.setText(getString(R.string.cancel_order), getString(R.string.confirm_cancel_order), getString(R.string.think), getString(R.string.confirm_cancel));
    }

    public void initCtrl(List<CheckComboResponseModel.ServiceAttrModel> items) {
        EmptyRecyclerCommonAdapter<CheckComboResponseModel.ServiceAttrModel> adapter = new EmptyRecyclerCommonAdapter<CheckComboResponseModel.ServiceAttrModel>(context, R.layout.item_confirm_order_service_layout, items) {
            @Override
            public void convert(RecyclerViewHolder holder, CheckComboResponseModel.ServiceAttrModel item, int position) {
                if (item.getServiceType() == 0) {
                    holder.setText(R.id.tv_service_name, item.getServiceName() + " * 1");
                } else {
                    // 月12，年1
                    holder.setText(R.id.tv_service_name, item.getServiceName() + " * " + item.getBookPeriod() + getString(item.getServicePeriod() == 12 ? R.string.month : R.string.year));
                }
                holder.setText(R.id.tv_service_price, getString(R.string.price, item.getPrice()));
            }
        };
        binding.includeService.recyclerViewService.setAdapter(adapter);
    }

    private void alipay(String info) {
        // 订单信息
        final String orderInfo = info;
        Runnable payRunnable = () -> {
            PayTask alipay = new PayTask(OrderDetailsActivity.this);
            Map<String, String> result = alipay.payV2(orderInfo, true);
            Message msg = new Message();
            msg.what = SDK_PAY_FLAG;
            msg.obj = result;
            mHandler.sendMessage(msg);
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private final MyHandler mHandler = new MyHandler(Looper.myLooper(), this);

    private static class MyHandler extends Handler {

        WeakReference<OrderDetailsActivity> mActivity;

        public MyHandler(@NonNull Looper looper, OrderDetailsActivity activity) {
            super(looper);
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == SDK_PAY_FLAG) {
                @SuppressWarnings("unchecked") PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                String resultInfo = payResult.getResult();// 同步返回需要验签的信息，对应map集合中key为result对应的value值。
                String resultStatus = payResult.getResultStatus();
                Bundle bundle = new Bundle();
                if (TextUtils.equals(resultStatus, "9000")) {
                    // 同步通知验证,在返回数据resultStatus为9000的情况下，继续解析resultInfo字符串，进行验签
                    ToastHelper.show("验签通过后才能证明支付成功" + payResult);
                    bundle.putInt(Constant.RESULT_STATUS_KEY, 1);
                } else if (TextUtils.equals(resultStatus, "6001")) {
                    bundle.putInt(Constant.RESULT_STATUS_KEY, -1);
//                    ToastHelper.show("支付取消==");
                } else {
                    bundle.putInt(Constant.RESULT_STATUS_KEY, -1);
//                    ToastHelper.show("支付失败==");
                }
                JumpIntent.jump(mActivity.get(), OrderResultActivity.class, bundle);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(EventBusModel eventBusModel) {
        if (null != eventBusModel) {
            if (Constant.finishOrderDetailsPage.equals(eventBusModel.getMessage())) {
                finish();
            }
        }
    }
}